
package cn.org.seventh.common;

import java.io.ByteArrayInputStream;
import java.io.CharArrayWriter;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.sql.Clob;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author <a href="mailto:ji.li@symbio-group.com">Andy</a>
 * @since Nov 30, 2007 4:17:04 PM
 */
public final class SQLUtil {

    private static Log log = LogFactory.getLog(SQLUtil.class);

    public static String getStringFromClob(Clob clob) {
        String value = null;
        if (clob != null) {
            // ByteArrayOutputStream out = new ByteArrayOutputStream();
            CharArrayWriter out = new CharArrayWriter();
            Reader in = null;
            try {
                in = clob.getCharacterStream();
                char[] buf = new char[8192];
                int len = 0;
                while ((len = in.read(buf, 0, buf.length)) != -1) {
                    out.write(buf, 0, len);
                }
                value = out.toString();
                in.close();
                in = null;
                out.close();
                out = null;
            } catch (Exception e) {
                log.debug(e);
                if (in != null) {
                    try {
                        in.close();
                    } catch (Throwable t) {
                    }
                }
                if (out != null) {
                    try {
                        out.close();
                    } catch (Throwable t) {
                    }
                }
            }
        }
        return value;
    }

    public static void setStringToClob(Clob clob, String s) {
        if (clob == null || s == null) {
            return;
        }
        OutputStream out = null;
        InputStream in = null;
        try {
            out = clob.setAsciiStream(0);
            in = new ByteArrayInputStream(s.getBytes());
            byte[] buf = new byte[8192];
            int len = 0;
            while ((len = in.read(buf, 0, buf.length)) != -1) {
                out.write(buf, 0, len);
            }
            in.close();
            in = null;
            out.close();
            out = null;
        } catch (Exception e) {
            log.debug(e);
            if (in != null) {
                try {
                    in.close();
                } catch (Throwable t) {
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (Throwable t) {
                }
            }
        }
    }
}
